package com.zephyr.vchcenter.service.thread;

import java.util.Vector;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadManager {

	private Vector data;
	private final int MIX_POOL_SIZE = 1;
	private final int MAX_POOL_SIZE = 2;
	private final int keepAliveTime = 10;
	private final TimeUnit unit = TimeUnit.SECONDS;
	private final int QueueSize = 2;
	private ThreadPoolExecutor threadPool;

	public ThreadManager() {
		this.threadPool = new ThreadPoolExecutor(MIX_POOL_SIZE, MAX_POOL_SIZE,
				keepAliveTime, unit,
				new ArrayBlockingQueue<Runnable>(QueueSize),
				new ThreadPoolExecutor.AbortPolicy());
		if (data == null)
			data = new Vector();
	}

	public synchronized void setData(Vector data) {
		System.out.println(data.size() + " size of data has been inserted..");
		for (int i = 0; i < data.size(); i++) {
			this.data.add(data.get(i));
		}
	}

	public synchronized Object getData() {
		Object obj;
		if (this.data.size() <= 0)
			return null;
		else {
			obj = this.data.firstElement();
			//System.out.println("object[ " + obj + " ]has been removed");
			this.data.remove(obj);
		}
		return obj;
	}

	public void server() throws InterruptedException {
		while (true) {
			try {
				//if (this.data.size() > 0)
					//System.out.println("size:" + this.data.size());
				Object obj = getData();
				threadPool.execute(new Worker(obj,this.data.size()));
				//Thread.sleep((long) (Math.random() * 1000));
			} catch (RejectedExecutionException e) {
				//System.out.println("等待任务.....");
				Thread.sleep(3000);
			}
		}
	}

	class Worker implements Runnable // 工作线程，线程要完成的工作在此类中实现
	{
		Object obj;
		int size;
		
		Worker(Object obj,int size) {
			this.obj = obj;
			this.size = size;
		}

		public void run() {
			if (obj == null) {
				return;
			} else {
				try {
					System.out.println(size + " is the current data size.." +Thread.currentThread().getName());
					Thread.sleep((long) (Math.random() * 1));
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
